import React, { memo, useEffect, useState } from "react";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Button, Form, Input, Modal, Table, Space, TreeSelect, message, Radio, InputNumber } from "antd";
import { ResultEnum } from "@/enums/httpEnum";
import useAuthPermission from "@/hooks/useAuthPermission";
import { getAuthMenuList, createMenu, deleteMenu, updateMenu } from "@/api/modules/menu";
import { IMenuItem } from "@/api/interface/auth";
// import { processMenus } from "@/utils/util";
import "./index.less";

// eslint-disable-next-line react/display-name
const MenuManage = memo(() => {
	// 按钮权限
	const [menuList, setMenuList] = useState<Menu.MenuOptions[] | undefined>([]);
	// 新建框
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [form] = Form.useForm();
	const [submitting, setSubmitting] = useState(false);
	const [editId, setEditId] = useState<number | null>(null);

	const formDefaultValues = {
		icon: "AppstoreOutlined",
		isDirectory: 0,
		sortNumber: 1
	};
	const onFinish = () => {
		form.resetFields();
	};
	const createModal = () => {
		form.resetFields();
		setIsModalOpen(true);
	};

	const handleOk = () => {
		setIsModalOpen(false);
	};

	const handleCancel = () => {
		setEditId(null);
		setIsModalOpen(false);
	};

	const editorForm = (formData: Menu.MenuOptions) => {
		form.setFieldsValue(formData);
		setEditId(formData.id);
		console.log(formData);
		setIsModalOpen(true);
	};

	const handleSubmit = async () => {
		try {
			await form.validateFields();
			setSubmitting(true);
			const values = await form.getFieldsValue();
			let submitFn: Function = createMenu;
			// console.log(values);
			const params = {
				...values
			};
			// console.log(editId);
			if (editId) {
				params.id = editId;
				submitFn = updateMenu;
			}

			const { code, msg } = await submitFn(params);
			if (code === 200) {
				await getMenuList();
				message.success(msg);
				handleCancel();
				form.resetFields();
			}

			setSubmitting(false);
		} catch (err) {
			setSubmitting(false);
			// console.log(err);
		}
	};

	// 获取数据
	const getMenuList = async () => {
		const { code, data } = await getAuthMenuList();
		if (code === ResultEnum.SUCCESS) {
			setMenuList(data);
		}
		// console.log(menuList);
		// setMenuList(res);
	};

	useEffect(() => {
		getMenuList();
	}, []);

	const { confirm } = Modal;
	const showConfirm = (id: number) => {
		confirm({
			title: "提示",
			icon: <ExclamationCircleOutlined />,
			content: "确定删除当前菜单？此操作将会删除当前菜单与它的全部子菜单?",
			async onOk() {
				const { code, msg } = await deleteMenu(id);
				if (code === 200) {
					message.success(msg);
					await getMenuList();
				}
			},
			onCancel() {
				console.log("Cancel");
			}
		});
	};

	const columns: any[] = [
		{
			title: "菜单名称",
			dataIndex: "title",
			key: "id",
			align: "center"
		},
		{
			title: "菜单链接",
			dataIndex: "path",
			key: "path",
			align: "center"
		},
		{
			title: "序号",
			dataIndex: "sortNumber",
			key: "sortNumber",
			align: "center"
		},
		{
			title: "icon",
			dataIndex: "icon",
			key: "icon",
			align: "center"
		},
		{
			title: "创建人",
			dataIndex: "creator",
			key: "creator",
			align: "center",
			render: (creator: string, record: Menu.MenuOptions) => {
				return (
					<div>
						{creator}
						{record.nickname ? `(${record.nickname})` : ""}
					</div>
				);
			}
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center"
		},
		{
			title: "操作",
			dataIndex: "id",
			key: "id",
			render: (id: number, record: Menu.MenuOptions) => {
				return (
					<Space>
						{useAuthPermission("menu:update") && <a onClick={() => editorForm(record)}>编辑</a>}
						{useAuthPermission("menu:delete") && <a onClick={() => showConfirm(id)}>删除</a>}
					</Space>
				);
			},
			align: "center"
		}
	];
	return (
		<div className="card menu-manage-box">
			<div className="create">
				{useAuthPermission("menu:add") && (
					<Button type="primary" onClick={createModal}>
						添加菜单
					</Button>
				)}
			</div>
			<Table
				bordered={true}
				dataSource={menuList?.map(item => {
					return {
						...item,
						key: item.id
					};
				})}
				columns={columns}
				rowKey={record => record.id}
				pagination={false}
			/>
			<Modal
				title="新建菜单"
				open={isModalOpen}
				onOk={handleOk}
				onCancel={handleCancel}
				footer={[
					<Button key="back" onClick={handleCancel}>
						取消
					</Button>,
					<Button key="submit" type="primary" loading={submitting} onClick={handleSubmit}>
						确定
					</Button>
				]}
			>
				<Form<IMenuItem>
					initialValues={formDefaultValues}
					form={form}
					labelCol={{ span: 6 }}
					wrapperCol={{ span: 14 }}
					layout="horizontal"
					onFinish={onFinish}
				>
					<Form.Item label="菜单名称" name="title" rules={[{ required: true }]}>
						<Input />
					</Form.Item>
					<Form.Item label="菜单链接" name="path" rules={[{ required: true }]}>
						<Input />
					</Form.Item>
					<Form.Item label="排序号" name="sortNumber">
						<InputNumber min={0} max={10} name="sortNumber" />
					</Form.Item>
					<Form.Item label="Icon" name="icon" rules={[{ required: true }]}>
						<Input disabled />
					</Form.Item>

					<Form.Item label="选择菜单上级" name="parentId">
						<TreeSelect
							treeData={menuList
								?.filter(item => item.isDirectory)
								.map(item => {
									return {
										title: item.title,
										value: item.id,
										children:
											item.children
												?.filter(item => item.isDirectory)
												.map(item1 => {
													return {
														title: item1.title,
														value: item1.id
													};
												}) || []
									};
								})}
						/>
					</Form.Item>

					<Form.Item label="是否为目录" name="isDirectory" rules={[{ required: true }]}>
						<Radio.Group>
							<Radio value={1}> 是 </Radio>
							<Radio value={0}> 否 </Radio>
						</Radio.Group>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
});
export default MenuManage;
